<template>
  <div class="container">
    <div class="app-container">
      <el-tree
        :data="deptsData"
        :props="defaultProps"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{ data }">
          <el-row
            type="flex"
            justify="space-between"
            align="middle"
            style="width: 100%; height: 40px"
          >
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="manage">{{ data.managerName }}</span>
              <el-dropdown @command="handleCommand($event, data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <addDeptsVue
      ref="addDepts"
      :show-dialog.sync="showDialog"
      :current-id="currentId"
      @updateDeparment="getData"
    />
  </div>
</template>

<script>
import { delDepartment, getDeparment } from '@/api/deparment'
import { transList2TreeData } from '@/utils'
import addDeptsVue from './addDepts.vue'
export default {
  name: 'Department',
  components: {
    addDeptsVue
  },
  data() {
    return {
      deptsData: [],
      defaultProps: {
        label: 'name'
      },
      showDialog: false,
      currentId: null
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await getDeparment()
      this.deptsData = transList2TreeData(res, 0)
    },
    handleCommand(command, id) {
      // 添加部门
      if (command === 'add') {
        this.showDialog = true
        this.currentId = id
      } else if (command === 'edit') {
        this.currentId = id
        this.showDialog = true
        // 先更新props 然后在调用子组件方法
        this.$nextTick(() => {
          this.$refs.addDepts.getDetail()
        })
      } else {
        this.$confirm('确定删除此部门吗？').then(async() => {
          await delDepartment(id)
          this.$message.success('删除成功')
          this.getData()
        })
      }
    }
  }
}
</script>
<style scoped lang="scss">
.container {
  padding: 20px;
  .app-container {
    padding: 30px 140px;
    font-size: 14px;
  }
  .manage {
    width: 80px;
    display: inline-block;
    margin-right: 5px;
  }
}
</style>
